package com.link.base.base.product.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.product.model.PriceList;
import com.link.base.base.product.model.PriceListItem;
import com.link.base.base.product.service.PriceListItemService;
import com.link.base.base.product.service.PriceListService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 */
@Controller
@RequestMapping("/link/priceListItem")
public class PriceListItemController extends BasicController<PriceListItem> {

    @Resource
    private PriceListItemService priceListItemService;

    @Resource
    private PriceListService priceListService;

    @Override
    public BasicService<PriceListItem> getBasicService() throws Exception {
        return priceListItemService;
    }

    @Override
    public void beforQueryExample(PriceListItem entity, HttpServletRequest request) throws Exception {
        super.beforQueryExample(entity, request);
        if (entity.getHeadId() == null) {
            // 物料大类

            String headId = request.getParameter("headId");
            entity.setHeadId(StringUtils.isBlank(headId) ? 0L : Long.parseLong(headId));
        }
    }

    @Override
    @RequestMapping(value = "/preDefaultValue", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> preDefaultValue(PriceListItem entity, HttpSession session, HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            PriceListItem newEntity = new PriceListItem();
            SimpleDateFormat dfFormat = new SimpleDateFormat("yyyy-MM-dd-yyyy HH:mm:ss");
            Date myDate = new Date();
            String sysdate = dfFormat.format(myDate);
            newEntity.setEffStartDate(sysdate);
            result.put("success", true);
            result.put("result", newEntity);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 插入或更新前做操作
     */
    @Override
    public void beforUpsert(PriceListItem entity, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(entity.getEffStartDate())) {
            throw new Exception("有效开始时间不能为空");
        }
        if (entity.getPoint() != null && entity.getPoint() <= 0) {
            throw new ServiceException("PROPRICE-001");
        }
        List<PriceListItem> list = priceListItemService.queryByProdId(entity);
        SimpleDateFormat dfFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date sDate2 = dfFormat.parse(entity.getEffStartDate());
        Long id2 = entity.getId();
        // 有效结束时间不为空
        if (entity.getEffEndDate() != null && !"".equals(entity.getEffEndDate())) {
            Date eDate2 = dfFormat.parse(entity.getEffEndDate());
            // 判断有效开始时间和有效结束时间大小关系
            if (eDate2.getTime() < sDate2.getTime()) {
                throw new BasicControllerException("产品的有效结束时间不能比有效开始时间早，请重新编辑！");
            }
            // 比较相同产品的时间概率
            if (list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    //排除本身
                    if (list.get(i).getId().equals(entity.getId())) {
                        continue;
                    }
                    Date sDate1 = dfFormat.parse(list.get(i).getEffStartDate());
                    Long id1 = list.get(i).getId();
                    if (!id2.equals(id1)) {
                        if (list.get(i).getEffEndDate() != null) {
                            Date eDate1 = dfFormat.parse(list.get(i).getEffEndDate());
                            if (compareDate(sDate2, eDate1) == -1 && compareDate(eDate2, sDate1) == 1) {
                                throw new BasicControllerException("已存在相同产品并且有效期相同，不能重新创建！");
                            }
                        } else {
                            if (compareDate(eDate2, sDate1) == 1) {
                                throw new BasicControllerException("已存在相同产品并且有效期相同，不能重新创建！");
                            }
                        }
                    }
                }
            }
        } else { // 有效结束时间为空
            // 比较相同产品的时间概率
            if (list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    Long id1 = list.get(i).getId();
                    if (!id2.equals(id1)) {
                        if (list.get(i).getEffEndDate() != null) {
                            Date eDate1 = dfFormat.parse(list.get(i).getEffEndDate());
                            if (compareDate(sDate2, eDate1) == -1) {
                                throw new BasicControllerException("已存在相同产品并且有效期相同，不能重新创建！");
                            }
                        } else {
                            throw new BasicControllerException("已存在相同产品并且有效期相同，不能重新创建！");
                        }
                    }
                }
            }
        }

    }

    public int compareDate(Date dt1, Date dt2) {
        if (dt1.getTime() > dt2.getTime()) {
            return 1;
        } else if (dt1.getTime() < dt2.getTime()) {
            return -1;
        } else {
            // 相等
            return 0;
        }
    }

    @RequestMapping(value = "/multiAddProdToPrice", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> multiAddProdToPrice(@RequestBody List<PriceListItem> priceListItemList, QueryParams qps,
                                                   HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            for (int i = 0; priceListItemList != null && i < priceListItemList.size(); i++) {
                PriceListItem priceListItem = priceListItemList.get(i);
                //获取1小时前的时间，降低系统时间不准确的风险
                Date tempDate = DateUtil.addTimes(Calendar.HOUR, new Date(), -1);
                Date tempDate1 = DateUtil.addTimes(Calendar.DATE, new Date(), -1);
                String effStartDate = DateUtil.dateToStr(tempDate1, "yyyy-MM-dd HH:mm:ss");
                String effEndDate = DateUtil.dateToStr(tempDate, "yyyy-MM-dd HH:mm:ss");
                /**
                 * @author 张宇浩
                 * @apiNote 新增产品开始|结束时间为价格表有效时间
                 */
                priceListItemService.insert(priceListItem);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询当前登录人的经销商的一条销售价格表
     */
    @RequestMapping(value = "/queryDealerSalePriceHead")
    @ResponseBody
    public Map<String, Object> queryDealerSalePriceHead(@RequestBody PriceListItem entity, HttpSession session,
                                                        HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            PriceList record = priceListService.queryDealerSalePriceHead(user.getAcctId());
            result.put("result", record);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 上架或下架价格行表数据
     */
    @RequestMapping(value = "/onOrOffPriceItem")
    @ResponseBody
    public Map<String, Object> onOrOffPriceItem(@RequestBody PriceListItem entity, HttpSession session,
                                                HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        String base = "base";
        try {
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-002");
            }
            priceListItemService.onOrOffPriceItem(entity);
            PriceListItem newEntry = getBasicService().queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
